﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DbUpgradeDameng.General
{
    public class ConfigManager
    {
        private IConfiguration config;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="filename">指定的配置文件</param>
        public ConfigManager(string filename)
        {
            config = new ConfigurationBuilder()
                .AddInMemoryCollection()//将配置文件的数据加载到内存中
                .SetBasePath(GetRootMapPath(""))//指定配置文件所在的目录
                .AddJsonFile(filename, optional: true, reloadOnChange: true)  //指定加载的配置文件
                .Build();
        }

        public T GetConfig<T>(string key) where T : class, new()
        {
            IConfigurationSection section = config.GetSection(key);
            var appconfig = new ServiceCollection()
            .AddOptions()
            .Configure<T>(section)
            .BuildServiceProvider()
            .GetService<IOptions<T>>()
            .Value;

            return appconfig;
        }

        private string GetRootMapPath(string strPath)
        {
            string rootDir = AppContext.BaseDirectory;

            string dir = string.Empty;
            if (!string.IsNullOrEmpty(strPath))
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart(new char[]
                    {
                    '\\'
                    });
                }
                dir = Path.Combine(rootDir, strPath);
            }
            else
            {
                dir = rootDir;
            }

            return dir;
        }
    }
}
